import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    tabList: [
      '热门精选',
      '无肉不欢',
      '健康时蔬',
      '佳米主食',
      '畅爽饮料',
    ],

    title: '',
    maxLinePrice: '',
    minSalePrice: '',
    residueNum: '',
    spusologen: '',
    tag: [],
    primaryImage: '',
    images: [],
    fileList: [],
    specNum: 0,
    specList: [],

    isEdit: false,
    spuId: '',
    editInfo: {}
  },
  async onLoad(options) {
    if (options.spuId) {
      this.setData({
        isEdit: true,
        spuId: options.spuId
      })
      const db = wx.cloud.database();
      const { data: [info] } = await db.collection('goodList').where({
        _id: options.spuId
      }).get();
      const { title,
        maxLinePrice,
        minSalePrice,
        residueNum,
        spuTagList,
        tag,
        images,
        desc,
        specList } = info
      this.setData({
        title,
        maxLinePrice: maxLinePrice / 100,
        minSalePrice: minSalePrice / 100,
        residueNum,
        spusologen: spuTagList ? spuTagList[0]?.title : '',
        tag: [{ key: tag[0], label: this.data.tabList[tag[0]] }],
        images: [{ url: images[0] }],
        fileList: desc.map(i => ({ url: i })),
        specList,
        specNum: specList.length
      })
    }
  },
  onInput({ detail, target }) {
    this.setData({
      [target.dataset.type]: detail.value
    })
  },
  handle2AddSpec() {
    const { specNum, specList } = this.data
    specList.push({
      title: '',
      specValueList: [],
      specId: new Date().getTime(),
      specValue: ''
    })
    this.setData({
      specNum: specNum + 1
    })
  },
  onSpecInput({ detail, target }) {
    const { specList } = this.data
    specList[target.dataset.index].title = detail.value
    this.setData({
      specList
    })
  },
  onSpecValueInput({ detail, target }) {
    const { specList } = this.data
    specList[target.dataset.index].specValue = detail.value
    this.setData({
      specList
    })
  },
  handleAddSpecValue({ target }) {
    const { specList } = this.data
    if (!specList[target.dataset.index].title) {
      wx.showToast({
        title: '请填写规格名称',
        icon: 'none'
      });
      return
    }
    if (!specList[target.dataset.index].specValue) {
      wx.showToast({
        title: '请填写规格值',
        icon: 'none'
      });
      return
    }
    specList[target.dataset.index].specValueList.push({
      specValue: specList[target.dataset.index].specValue,
      specValueId: new Date().getTime(),
    })
    this.setData({
      specList,
    })
    specList[target.dataset.index].specValue = ''
    this.setData({
      specList,
    })
  },
  handleDelSpec({ target: { dataset } }) {
    const { specList, specNum } = this.data
    specList.splice(dataset.index, 1)
    this.setData({
      specList,
      specNum: specNum - 1
    })
  },
  handleClosetag({ target: { dataset } }) {
    console.log(dataset);
    const { specList } = this.data
    specList[dataset.index].specValueList.splice(dataset.tag, 1)
    this.setData({
      specList,
    })
  },
  tabChange({ detail }) {
    this.setData({
      tag: [{ key: +detail.value, label: this.data.tabList[detail.value] }]
    })
  },
  async handleAdd({ detail, target }) {
    const { fileList } = this.data;
    const { files } = detail;
    const { dataset: { type } } = target;
    if (type === 'primary') {
      this.setData({
        images: [...files.map(i => ({ ...i, status: 'loading' }))]
      })
      const result = await this.uploadImg(files[0].url)
      files[0].url = result
      files[0].status = 'done'
      this.setData({
        images: files
      })
      return
    }
    this.setData({
      fileList: [...fileList, ...files.map(i => ({ ...i, status: 'loading' }))], // 此时设置了 fileList 之后才会展示选择的图片
    });
    for (let i = 0; i < files.length; i++) {
      files[i].status = 'loading'
      const result = await this.uploadImg(files[i].url)
      files[i].status = 'done'
      files[i].url = result
    }
    this.setData({
      fileList: [...fileList, ...files]
    })
  },
  async uploadImg(filePath) {
    const { fileID } = await wx.cloud.uploadFile({
      cloudPath: new Date().getTime().toString(),
      filePath // 文件路径
    })
    const { fileList } = await wx.cloud.getTempFileURL({
      fileList: [fileID]
    })
    return fileList[0]?.tempFileURL
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { fileList } = this.data;

    fileList.splice(index, 1);
    this.setData({
      fileList,
    });
  },

  async handle2Submit() {
    const {
      title,
      maxLinePrice,
      minSalePrice,
      residueNum,
      spusologen,
      tag,
      images,
      fileList,
      specList
    } = this.data
    if (!title || !maxLinePrice || !minSalePrice || !residueNum || !tag || !images.length || !fileList.length) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return
    }
    const noSpecValue = specList.find(i => {
      return !i.specValueList.length
    })
    if (noSpecValue) {
      wx.showToast({
        title: `规格"${noSpecValue.title}"的规格值为空`,
        icon: 'none'
      })
      return
    }
    const req = {
      title,
      maxLinePrice: maxLinePrice * 100,
      minSalePrice: minSalePrice * 100,
      residueNum: +residueNum,
      spuTagList: [{ title: spusologen }],
      tag: [tag[0]?.key],
      primaryImage: images[0]?.url,
      images: [images[0]?.url],
      desc: fileList.map(i => i.url),
      specList
    }
    const db = wx.cloud.database();
    if (this.data.isEdit) {
      await db.collection('goodList').where({
        _id: this.data.spuId
      }).update({
        data: req
      });
    } else {
      await db.collection('goodList').add({
        data: {
          ...req,
          soldNum: 0,//销量
        },
      });
    }
    wx.showToast({
      title: '操作成功',
    });
    this.timer = setTimeout(wx.navigateBack, 1000)
  },
  async handle2Del() {
    wx.showModal({
      title: '确定删除该菜品',
      success: async ({ confirm }) => {
        if (confirm) {
          const db = wx.cloud.database();
          await db.collection('goodList').where({ _id: this.data.spuId }).remove();
          wx.showToast({
            title: '操作成功',
          });
          this.timer = setTimeout(wx.navigateBack, 1000)
        }
      }
    })
  },
  onUnload() {
    clearTimeout(this.timer)
  }
});
